package com.sqly.doc.menu.jzyy;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.support.annotation.IdRes;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ihidea.multilinechooselib.MultiLineChooseLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.grjbxx.jm_info_add;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.SeeDoctorOrder;
import com.sqly.doc.pojo.Xx;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.CustomDatePicker;
import com.sqly.doc.view.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import cxy.com.validate.IValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.MaxLength;
import cxy.com.validate.annotation.NotNull;
import cz.msebera.android.httpclient.Header;

public class jzyy_add extends MyBaseActivity {
    @Index(1)
    @NotNull(msg = "预约日期不能为空")
    @Bind(R.id.yyrq)
    EditText yyrq;

    @Index(2)
    @NotNull(msg = "居民不能为空")
    @Bind(R.id.jmname)
    @MaxLength(length = 20, msg = "最大长度为20个字符")
    EditText jmname;

    @Index(3)
    @NotNull(msg = "医生不能为空")
    @Bind(R.id.ysname)
    @MaxLength(length = 20, msg = "最大长度为20个字符")
    EditText ysname;

    @Index(4)
    @Bind(R.id.zhusu)
    @MaxLength(length = 40, msg = "最大长度为40个字符")
    EditText zhusu;

    @Index(5)
    @Bind(R.id.bsnr_qt)
    @MaxLength(length = 20, msg = "病史其他最大长度为20个字符")
    EditText bsnr_qt;

    @Index(6)
    @Bind(R.id.fbrq)
    EditText fbrq;

    @Index(6)
    @Bind(R.id.yysjd)
    Spinner yysjd;

    MultiLineChooseLayout bsnr;//服务内容
    private List<String> bsnrData = new ArrayList<>();
    private CustomDatePicker customDatePicker;
    Context con = jzyy_add.this;
    //标题
    TextView title, uname;
    SeeDoctorOrder obj;
    String url = "";
    LinearLayout bs_qt_ll;
    LinearLayout back;

    @Override
    protected void initUI() {
        setContentView(R.layout.jzyy_add);
        ButterKnife.bind(this);
        Validate.reg(this);
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (SeeDoctorOrder) getIntent().getExtras().getSerializable("b");
            url = HttpUrl.EditJzyy;
        } else {
            url = HttpUrl.AddJzyy;
            obj = new SeeDoctorOrder();
        }
        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void init() {
        bs_qt_ll = (LinearLayout) findViewById(R.id.bs_qt_ll) ;
        //bsnr_qt = (EditText) findViewById(R.id.bsnr_qt);
        if (obj != null && !StringUtils.isEmpty(obj.getJws_qt())) {
            bsnr_qt.setText(obj.getJws_qt());
        }
        //bz = (EditText) findViewById(R.id.bz);
        if (obj != null && !StringUtils.isEmpty(obj.getReservation_name())) {
            jmname.setText(obj.getReservation_name());
        }

        if (obj != null && !StringUtils.isEmpty(obj.getDoctor_name())) {
            ysname.setText(obj.getDoctor_name());
        }

        //yyrq = (EditText) findViewById(R.id.yyrq);
        if (obj != null && !StringUtils.isEmpty(obj.getTbtime())) {
            yyrq.setText(DateConvert.dateToString(DateConvert.toDate(obj.getTbtime(), DateConvert.YMD), DateConvert.YMD)+"");
        }
        yyrq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        yyrq.setText(time.split(" ")[0]);
                    }
                }, DateConvert.getCustomDatePickerStartRq(), DateConvert.getCustomDatePickerEndRq()); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(DateConvert.getCustomDatePickerStartRq());
            }
        });

        if (obj != null && !StringUtils.isEmpty(obj.getFbrq())) {
            fbrq.setText(DateConvert.dateToString(DateConvert.toDate(obj.getFbrq(), DateConvert.YMD), DateConvert.YMD)+"");
        }
        fbrq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        fbrq.setText(time.split(" ")[0]);
                    }
                }, DateConvert.getCustomDatePickerStartRq(), DateConvert.getCustomDatePickerEndRq()); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(DateConvert.getCustomDatePickerStartRq());
            }
        });

        if (obj != null && !StringUtils.isEmpty(obj.getMain_complaint())) {
            zhusu.setText(obj.getMain_complaint());
        }

        //文化程度
        Resources res = getResources();
        String[] whs = res.getStringArray(R.array.sjd);
        List<Xx> xxlist = new ArrayList<Xx>();
        for (int i = 0; i < whs.length; i++) {
            Xx x = new Xx();
            x.setName(whs[i]);
            xxlist.add(x);
        }
        yysjd.setAdapter(new CommonAdapter<Xx>(jzyy_add.this, xxlist, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, Xx item) {
                helper.setText(R.id.name, item.getName());
            }
        });
        if (obj != null && !StringUtils.isEmpty(obj.getPeriod())) {
            if(null != obj.getPeriod() && "8:00~9:00".equals(obj.getPeriod())) {
                yysjd.setSelection(0);
            }else if(null != obj.getPeriod() && "9:00~10:00".equals(obj.getPeriod())) {
                yysjd.setSelection(1);
            }else if(null != obj.getPeriod() && "10:00~11:00".equals(obj.getPeriod())) {
                yysjd.setSelection(2);
            }else if(null != obj.getPeriod() && "11:00~12:00".equals(obj.getPeriod())) {
                yysjd.setSelection(3);
            }else if(null != obj.getPeriod() && "11:00~12:00".equals(obj.getPeriod())) {
                yysjd.setSelection(4);
            }else if(null != obj.getPeriod() && "14:00~15:00".equals(obj.getPeriod())) {
                yysjd.setSelection(5);
            }else if(null != obj.getPeriod() && "15:00~16:00".equals(obj.getPeriod())) {
                yysjd.setSelection(6);
            }else if(null != obj.getPeriod() && "16:00~17:00".equals(obj.getPeriod())) {
                yysjd.setSelection(7);
            }
        }else{
            yysjd.setSelection(0);
        }
        yysjd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0) {
                    obj.setPeriod("8:00~9:00");
                }else if(position == 1) {
                    obj.setPeriod("9:00~10:00");
                }else if(position == 2) {
                    obj.setPeriod("10:00~11:00");
                }else if(position == 3 ) {
                    obj.setPeriod("11:00~12:00");
                }else if(position == 4 ) {
                    obj.setPeriod("11:00~12:00");
                }else if(position == 5 ) {
                    obj.setPeriod("14:00~15:00");
                }else if(position == 6 ) {
                    obj.setPeriod("15:00~16:00");
                }else if(position == 7) {
                    obj.setPeriod("16:00~17:00");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        bsnr = (MultiLineChooseLayout) findViewById(R.id.bsnr);
        bsnrData.add("无");
        bsnrData.add("高血压");
        bsnrData.add("糖尿病");
        bsnrData.add("冠心病");
        bsnrData.add("慢性阻塞性肺疾病");
        bsnrData.add("恶性肿瘤");
        bsnrData.add("脑卒中");
        bsnrData.add("严重精神障碍");
        bsnrData.add("结核病");
        bsnrData.add("肝炎");
        bsnrData.add("其他法定传染病");
        bsnrData.add("职业病");
        bsnrData.add("其他");
        bsnr.setList(bsnrData);

        if (obj != null && !StringUtils.isEmpty(obj.getJws())) {
            if (obj.getJws().contains(",")) {
                String[] ss = obj.getJws().split(",");
                for (int i = 0; i < ss.length; i++) {
                    if (!StringUtils.isEmpty(ss[i])) {
                        if(Integer.parseInt(ss[i])==0){
                            bsnr.setIndexItemSelected(Integer.parseInt(ss[i]));
                        }else{
                            bsnr.setIndexItemSelected(Integer.parseInt(ss[i])-1);
                        }
                        if(Integer.parseInt(ss[i])==12){
                            bs_qt_ll.setVisibility(View.VISIBLE);
                        }
                    }
                }
            } else {
                if(Integer.parseInt(obj.getJws())==0){
                    bsnr.setIndexItemSelected(Integer.parseInt(obj.getJws()));
                }else{
                    bsnr.setIndexItemSelected(Integer.parseInt(obj.getJws())-1);
                }
                if(Integer.parseInt(obj.getJws())==12){
                    bs_qt_ll.setVisibility(View.VISIBLE);
                }
            }
        }else{
            bsnr.setIndexItemSelected(0);
        }
        //单选
        bs_qt_ll.setVisibility(View.VISIBLE);
        bsnr.setOnItemClickListener(new MultiLineChooseLayout.onItemClickListener() {
            @Override
            public void onItemClick(int position, String text) {
//               if("其他".equals(text) && bs_qt_ll.getVisibility() == View.GONE){
//                   bs_qt_ll.setVisibility(View.VISIBLE);
//               }else if("其他".equals(text) && bs_qt_ll.getVisibility() == View.VISIBLE){
//                   bs_qt_ll.setVisibility(View.GONE);
//                   bsnr_qt.setText("");
//               }
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("就诊预约");
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        uname.setText("保存");
        uname.setText("");
        /*uname.setClickable(false);

        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<Integer> nrlist = bsnr.getAllItemSelectedIndex();
                String bsnrStrs = "", bsnrNameStrs = "";
                for (int i = 0; i < nrlist.size(); i++) {
                    if (i == 0) {
                        bsnrStrs = (nrlist.get(i) + 1) + "";
                        bsnrNameStrs = "无";
                    }else {
                        bsnrStrs = bsnrStrs + "," + (nrlist.get(i) + 1);
                        Integer wz = nrlist.get(i);
                        if(wz == 1) {
                            bsnrNameStrs = bsnrNameStrs + "," + "高血压";
                        }else if(wz == 2) {
                            bsnrNameStrs = bsnrNameStrs + "," + "糖尿病";
                        }else if(wz == 3) {
                            bsnrNameStrs = bsnrNameStrs + "," + "冠心病";
                        }else if(wz == 4) {
                            bsnrNameStrs = bsnrNameStrs + "," + "慢性阻塞性肺疾病";
                        }else if(wz == 5) {
                            bsnrNameStrs = bsnrNameStrs + "," + "恶性肿瘤";
                        }else if(wz == 6) {
                            bsnrNameStrs = bsnrNameStrs + "," + "脑卒中";
                        }else if(wz == 7) {
                            bsnrNameStrs = bsnrNameStrs + "," + "严重精神障碍";
                        }else if(wz == 8) {
                            bsnrNameStrs = bsnrNameStrs + "," + "结核病";
                        }else if(wz == 9) {
                            bsnrNameStrs = bsnrNameStrs + "," + "肝炎";
                        }else if(wz == 10) {
                            bsnrNameStrs = bsnrNameStrs + "," + "其他法定传染病";
                        }else if(wz == 11) {
                            bsnrNameStrs = bsnrNameStrs + "," + "职业病";
                        }else if(wz == 12) {
                            bsnrNameStrs = bsnrNameStrs + "," + "其他";
                        }
                    }
                }
                final String finalbsnrStrs = bsnrStrs, finalbsnrNameStrs = bsnrNameStrs;
                Validate.check(con, new IValidateResult() {
                    @Override
                    public void onValidateSuccess() {
                        //Toast.makeText(con, "验证成功", Toast.LENGTH_SHORT).show();
                        saveData(finalbsnrStrs, finalbsnrNameStrs);
                    }

                    @Override
                    public void onValidateError(String msg, View view) {
                        view.setFocusable(true);
                        //Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
                        SweetAlertDialogUtil.WarningDialog(con, "提示", msg);
                    }

                    @Override
                    public Animation onValidateErrorAnno() {
//                        return ValidateAnimation.horizontalTranslate();
                        return null;
                    }
                });
            }
        });
        */
    }

    @Override
    protected void initData() {

    }
    @Override
    protected void initListener() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Validate.unreg(this);
    }

    private void saveData(String finalbsnrStrs, String finalbsnrNameStrs){
        //保存
        if(null == finalbsnrStrs || "".equals(finalbsnrStrs)){
            SweetAlertDialogUtil.WarningDialog(con, "提示", "请选择病史");
        } else {
            if (obj == null)
                obj = new SeeDoctorOrder();
            obj.setJws(finalbsnrStrs);
            obj.setJws_name(finalbsnrNameStrs);
            obj.setJws_qt(bsnr_qt.getText().toString());
            obj.setTbtime(yyrq.getText().toString());
            obj.setReservation_name(jmname.getText().toString());
            obj.setReservation_name(jmname.getText().toString());
            obj.setFbrq(fbrq.getText().toString());
            if (NetWorkUtils.isNetworkConnected(con)) {
                RequestParams ps = new RequestParams();
                ps.add("entity.reservation_id", "");
                ps.add("entity.reservation_name", obj.getReservation_name());
                ps.add("entity.doctor_id", "");
                ps.add("entity.doctor_name", obj.getDoctor_name());
                ps.add("entity.period", obj.getPeriod());
                ps.add("entity.main_complaint", obj.getMain_complaint());
                ps.add("entity.jws", obj.getJws());
                ps.add("entity.jws_name", obj.getJws_name());
                ps.add("entity.jws_qt", obj.getJws_qt());
                ps.add("entity.fbrq", obj.getFbrq());
                if (getIntent().getStringExtra("type").equals("edit"))
                    ps.add("entity.id", obj.getSpid());
                ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                ps.add("type", "2");
                UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        String content = new String(response);
                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                        if (ret.getCode().equals("200")) {
                            MyToastUtil.ShowToast(con, "成功");
                        }else{
                            MyToastUtil.ShowToast(con, ret.getInfo());
                        }
                        finish();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                        MyToastUtil.ShowToast(con, "失败");
                    }
                });
            }
        }
    }
}
